package org.zffc.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description:
 * @Note: 黑名单过滤器
 * @Author: zhangfei
 * @Date: 2025/2/25 11:36
 **/
@Component
public class BlacklistFilter implements GlobalFilter, Ordered {
//    private final String[] blackListIps = {"192.168.68.108","0:0:0:0:0:0:0:1"}; // 黑名单IP列表
private final String[] blackListIps = {};

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 如果获取到的地址是 0:0:0:0:0:0:0:1，获取到的IP地址为 0:0:0:0:0:0:0:1 通常表示请求是通过本地回环地址（loopback address）发起的，
        // 这在IPv6中对应的是 ::1。在某些情况下，特别是在开发环境中，当你从同一台机器上的浏览器访问应用时，可能会看到这样的IP地址。
        String clientIp = getClientIp(exchange);
        System.out.println("clientIp:"+clientIp);
        for (String ip : blackListIps) {
            if (clientIp.equals(ip)) {
                exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
                return exchange.getResponse().setComplete();
            }
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -100; // 设置优先级
    }

    /**
     * 获取真实地址
     * @author zhangfei
     * @date 2025/2/25 11:42
     * @param exchange
     * @return
     */
    private String getClientIp(ServerWebExchange exchange) {
        String xForwardedFor = exchange.getRequest().getHeaders().getFirst("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
            // X-Forwarded-For 可能包含多个IP地址，取第一个
            String[] ips = xForwardedFor.split(",");
            return ips[0].trim();
        }
        return exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
    }
}
